package com.yeskery.nut.view.thymeleaf;

import com.yeskery.nut.core.MediaType;
import com.yeskery.nut.core.NutException;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.Response;
import com.yeskery.nut.view.BaseWebRender;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.util.Map;

/**
 * Thymeleaf的web渲染器
 * @author sprout
 * 2022-07-07 14:46
 */
public class ThymeleafWebRender extends BaseWebRender {

    /** 模板引擎 */
    private final TemplateEngine templateEngine;

    /**
     * 构建Thymeleaf的web渲染器
     * @param templateEngine 模板引擎
     * @param mediaType 媒体类型
     */
    public ThymeleafWebRender(TemplateEngine templateEngine, MediaType mediaType) {
        super(mediaType);
        this.templateEngine = templateEngine;
    }

    /**
     * 构建Thymeleaf的web渲染器
     * @param templateEngine 模板引擎
     * @param mediaType 媒体类型
     * @param extendAttributes 扩展属性
     */
    public ThymeleafWebRender(TemplateEngine templateEngine, MediaType mediaType, Map<String, ?> extendAttributes){
        super(mediaType);
        super.extendAttributes = extendAttributes;
        this.templateEngine = templateEngine;
    }

    @Override
    public void render(String key, Request request, Response response) {
        try {
            Context context = new Context();
            context.setVariables(getBaseStringKeyAttributes(request));
            String result = templateEngine.process(key, context);
            response.write(result, mediaType);
        } catch (Exception e) {
            throw new NutException("Thymeleaf Render Failure.", e);
        }
    }
}
